<template>
  <div class="ec-config">
    <ContentWrap>
      <FormContainer :column="4">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="120px" @submit.native.prevent>
          <el-form-item prop="postCode" label="岗位">
            <SelectForDict :code.sync="formData.postCode" dict-type-code="DEPT_POST_CODE" placeholder="请选择岗位" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="receiver" label="用户名">
            <el-input v-model="formData.receiver" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="receiverName" label="用户姓名">
            <el-input v-model="formData.receiverName" placeholder="请输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item prop="officeCode" label="办事处名称" hidden>
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/office/ref/page"
              placeholder="请选择办事处"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.officeCode"
              @selectChange="handleOfficeSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="customCode" label="经销商/三方物流名称">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/dealer/ref/page"
              method="get"
              placeholder="请选择经销商"
              :params="{query:{officeCode:formData.officeCode},type:0}"
              lable-name="name"
              value-name="code"
              custom-name="codeOrName"
              :parent-id="formData.officeCode"
              :value.sync="formData.customCode"
              :disabled="!formData.officeCode"
              clearable
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="platformCode" label="电商平台">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/platform/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              :value.sync="formData.platformCode"
              @selectChange="handlePlatformChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="storeCode" label="电商店铺">
            <SearchSelectPicker
              url="/select-service/api/v1/eco/shop/page"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              :must-pid="true"
              :parent-id="formData.platformCode"
              :disabled="!formData.platformCode"
              :params="{query:{platformCode:formData.platformCode},type:0}"
              :value.sync="formData.storeCode"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="provinceCode" label="省">
            <SearchSelectPicker
              url="/call-center/api/v1/mscInfo/adminidiv"
              :remote="false"
              placeholder="请选择"
              lable-name="name"
              value-name="code"
              method="get"
              :value.sync="formData.provinceCode"
              @selectChange="handlerSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="state" label="启用状态">
            <SearchSelectPicker
              placeholder="请选择启用状态"
              lable-name="dictName"
              value-name="dictCode"
              :select-data="enableList"
              :value.sync="formData.state"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item more show>
            <Button @click="resetForm">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="btn-wrap">
        <AddOrEdit key="add" @on-refresh="handleRefresh"></AddOrEdit>
        <AddOrEdit key="edit" is-edit :selection="selection" @on-refresh="handleRefresh"></AddOrEdit>
        <!-- <Button type="primary" @click="handleImport">导入</Button> -->
        <ExportPane :table-config="tableConfig" :data-source="selection" :query-data-fun="queryHandle" filename="电商工单接收人配置表">导出</ExportPane>
        <Button type="primary" @click="handleUpdateEnable(1)">启用</Button>
        <Button type="primary" @click="handleUpdateEnable(0)">停用</Button>
        <Button type="primary" @click="handleRemove">删除</Button>
      </div>
      <table-box ref="tableBox" show-selection show-index no-request :other-filters="filtersRaw" :selected-arry.sync="selection" :table-config="tableConfig" @selection-change="handleSelectionChange"></table-box>
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import AddOrEdit from './components/AddOrEdit'
import ExportPane from '@/components/ExportPane'
import { disableBatch, enableBatch, deleteBatch, importEcConfig } from '@/api/ecRecipientConfig'
import { deepCopy } from '@/utils/'
import { ArrayFormat } from '@/utils/params-format'
export default {
  name: 'ECRecipientConfig',
  components: {
    ContentWrap,
    FormContainer,
    SelectForDict,
    SearchSelectPicker,
    AddOrEdit,
    ExportPane
  },
  data() {
    return {
      enableList: [
        { dictCode: '0', dictName: '停用' },
        { dictCode: '1', dictName: '启用' }
      ],
      formData: {
        postCode: '',
        receiver: '',
        receiverName: '',
        officeCode: '',
        customCode: '',
        platformCode: '',
        storeCode: '',
        provinceCode: '',
        provinceId: '', // 数据库中 provinceCode 字段可能有id
        state: ''
      },
      formRules: {

      },
      tableConfig: {
        interfacePath: `/call-center/api/v1/workOrderEcosReceiver/page`,
        tableIndex: 1,
        hideFuncBar: false,
        buttonGroupCode: 'default',
        // order: 'DESC',
        // sort: 'createTime',
        sortersRow: [
          { id: 'createTime', property: 'createTime', direction: 'DESC' },
          { id: 'state', property: 'state', direction: 'DESC' }
        ],
        setting: [
          {
            prop: 'postName',
            label: '岗位',
            minWidth: 120
          },
          {
            prop: 'receiver',
            label: '用户名',
            minWidth: 130
          },
          {
            prop: 'receiverName',
            label: '用户姓名',
            minWidth: 130
          },
          {
            prop: 'receiverPhone',
            label: '联系电话',
            minWidth: 100
          },
          {
            prop: 'officeCode',
            label: '办事处编码',
            minWidth: 110
          },
          {
            prop: 'officeName',
            label: '办事处名称',
            minWidth: 150
          },
          {
            prop: 'customCode',
            label: '经销商、三方物流编码',
            minWidth: 150
          },
          {
            prop: 'customName',
            label: '经销商/三方物流名称',
            minWidth: 150
          },
          {
            prop: 'platformName',
            label: '电商平台',
            minWidth: 120
          },
          {
            prop: 'storeName',
            label: '电商店铺',
            minWidth: 120
          },
          {
            prop: 'provinceName',
            label: '省',
            minWidth: 120
          },
          {
            prop: 'state',
            label: '启用状态',
            minWidth: 100,
            formatData(row) {
              return [1, '1'].includes(row.state) ? '启用' : '停用'
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 100
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 140
          },
          {
            prop: 'lastUpdateBy',
            label: '最近修改人',
            minWidth: 100
          },
          {
            prop: 'lastUpdateTime',
            label: '最近修改时间',
            minWidth: 140
          }
        ]
      },
      selection: [],
      filtersRaw: []
    }
  },
  computed: {
  },
  methods: {
    handleOfficeSelectChange() {
      this.$set(this.formData, 'customCode', '')
      this.$set(this.formData, 'customName', '')
    },
    handlePlatformChange() {
      this.$set(this.formData, 'storeCode', '')
      this.$set(this.formData, 'storeName', '')
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.provinceId = ''
    },
    queryHandle(type) {
      const data = deepCopy(this.formData)
      const { provinceCode, provinceId } = data
      const t = []
      provinceCode && t.push(provinceCode)
      provinceId && t.push(provinceId)
      delete data.provinceId
      data.provinceCode = `[${t.join(',')}]`
      const filtersRaw = [...ArrayFormat(data, {
        postCode: '=',
        receiver: '=',
        receiverName: 'like',
        officeCode: '=',
        customCode: '=',
        platformCode: '=',
        storeCode: '=',
        provinceCode: 'in',
        state: '='
      })]
      this.filtersRaw = filtersRaw
      if (type !== 'export') {
        this.refreshTable()
      }
      return filtersRaw
    },
    handleImport() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.xls,.xlsx'
      input.onchange = e => {
        if (e.target.files.length === 0) return
        const data = new FormData()
        data.append('file', e.target.files[0])
        importEcConfig(data).then(() => {
          this.refreshTable()
        })
      }
      input.click()
    },
    handleRefresh(type) {
      this.refreshTable(type)
    },
    refreshTable(type) {
      this.selection = []
      this.$nextTick(() => {
        this.$refs.tableBox && this.$refs.tableBox.initTableData(type)
      })
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleUpdateEnable(type) {
      if (!this.singleJudge(this.selection, type === 1 ? '启用' : '停用', false)) {
        return Promise.reject('')
      }
      const t = this.selection.map(e => e.state)
      if (type === 1 && (t.includes(1) || t.includes('1'))) {
        this.$message.warning('所选数据包含启用项!')
        return Promise.reject('')
      } else if (type === 0 && (t.includes(0) || t.includes('0'))) {
        this.$message.warning('所选数据包含停用项!')
        return Promise.reject('')
      }
      const ajax = type === 1 ? enableBatch : disableBatch
      return ajax(this.selection.map(e => e.id)).then(res => {
        this.$message.success('操作成功!')
        this.refreshTable('onPage')
      })
    },
    handleRemove() {
      if (!this.singleJudge(this.selection, '删除', false)) {
        return Promise.reject('')
      }
      const t = this.selection.map(e => e.state)
      if (t.includes(1) || t.includes('1')) {
        this.$message.warning('所选数据包含【启用】项,不能删除启用项!')
        return Promise.reject('')
      }
      return deleteBatch(this.selection.map(e => e.id)).then(res => {
        this.$message.success('操作成功!')
        this.refreshTable()
      })
    },
    // 省 变化
    handlerSelectChange(v) {
      this.$set(this.formData, 'provinceId', v ? v.id : '')
    }
  }
}
</script>
<style lang="scss" scoped>
.ec-config{
  .btn-wrap{
    &>*{
      margin: 0 10px 0 0;
    }
  }
}
</style>
